<template>
  <div class="cartcontrol">
    <transition name="move">
      <!-- clicl.prevent:组织浏览器默认行为     click.stop:阻止事件冒泡 -->
      <div class="iconfont icon-yichu" v-show="food.count" @click.stop="deleteFoodCount(false)"></div>
    </transition>
    <div class="cart-count" v-show="food.count">{{food.count}}</div>
    <div class="iconfont icon-tianjia" @click.stop="deleteFoodCount(true)"></div>
  </div>
</template>

<script>
import {mapState} from 'vuex'
import { Toast } from 'mint-ui'

export default {
  props: {
    food: Object
  },
  computed: {
    ...mapState(['cartFoods', 'userInfo'])
  },
  methods: {
    deleteFoodCount (isAdd) {
      if (this.userInfo._id) { // userInfo._id有值表示登录，登陆后才可以进行购物车操作
        // 用了vuex管理，所有对数据的操作都应该由action来操作；及时不用vuex管理，对数据的操作也应该在数据产生的组件

        // isadd为真则是调用增加,否则减少
        this.$store.dispatch('deleteFoodCount', {food: this.food, isAdd})

        /*
          如果isAdd为真，则增加，同时调用action将food也加入购物车中
          避免重复添加同一食物：将cartFoods转为Set集合，利用集合的has方法判断当前食物是否已经存入数组中，存在则不继续添加该食物，否则添加
        */
        const temp = new Set(this.cartFoods)
        let isExist = temp.has(this.food)
        if (isAdd && !isExist) { // 避免重复添加同一食物，同一食物数量添加不受影响
          this.$store.dispatch('addFoodToCart', {food: this.food})
        }
        // 减少食物
        if (!isAdd) {
          this.$store.dispatch('removeFoodToCart', {food: this.food})
        }
      } else {
        Toast('请先登录！')
        // 给用户一点反应时间再跳转
        setTimeout(() => { this.$router.push('/login') }, 500)
      }
    }
  }

}
</script>

<style lang="stylus" rel="stylesheet/stylus">
  @import "../../common/stylus/mixins.styl"
  .cartcontrol
    font-size: 0
    .cart-decrease
      display: inline-block
      padding: 6px
      line-height: 24px
      font-size: 24px
      color: rgb(65,184,131)

    .icon-yichu
      display: inline-block
      padding 6px
      line-height 24px
      font-size 24px
      color rgb(65,184,131)
      &.move-enter-active, &.move-leave-active
        transition all .4s
      &.move-enter, &.move-leave-to
        opacity 0
        transform translateX(15px) rotate(180deg)
    .cart-count
      display: inline-block
      vertical-align: top
      width: 12px
      padding-top: 6px
      line-height: 24px
      text-align: center
      font-size: 10px
      color: black
    .icon-tianjia
      display: inline-block
      padding: 6px
      line-height: 24px
      font-size: 24px
      color rgb(65,184,131)
</style>
